<script setup>
import { ref, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useDocumentStore } from '@/stores/document';

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  documentId: {
    type: [String, Number],
    required: true
  }
});

const emit = defineEmits(['update:visible', 'view-version', 'backtrack-success']);

const documentStore = useDocumentStore();
const loading = ref(false);
const versions = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 获取文档版本历史列表
const fetchVersions = async () => {
  loading.value = true;
  try {
    await documentStore.fetchDocumentVersions(
      props.documentId,
      currentPage.value,
      pageSize.value
    );
    versions.value = documentStore.documentVersions;
    total.value = documentStore.totalDocumentVersions;
  } catch (error) {
    ElMessage.error('获取文档版本历史失败');
    console.error('Failed to fetch document versions:', error);
  } finally {
    loading.value = false;
  }
};

// 查看特定版本
const viewVersion = async (version) => {
  emit('view-version', version);
  closeDialog();
};

// 删除特定版本
const deleteVersion = async (version) => {
  try {
    // 确认删除
    await ElMessageBox.confirm(
      `确定要删除版本 ${version.version} 吗？此操作不可恢复。`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    // 执行删除
    const result = await documentStore.deleteDocumentVersion(version.id);
    
    if (result) {
      ElMessage.success('删除版本成功');
      // 刷新版本列表
      fetchVersions();
    } else {
      ElMessage.error('无权限，删除版本失败');
    }
  } catch (err) {
    // 用户取消删除或发生错误
    if (err !== 'cancel') {
      console.error('Failed to delete version:', err);
    }
  }
};

// 回溯到特定版本
const backtrackVersion = async (version) => {
  try {
    // 确认回溯
    await ElMessageBox.confirm(
      `确定要回溯到版本 ${version.version} 吗？当前文档内容将被替换。`,
      '回溯确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    // 执行回溯
    const result = await documentStore.backtrackDocumentVersion(version.id, props.documentId);
    
    if (result) {
      ElMessage.success('回溯成功，文档已更新');
      // 发送回溯成功事件，通知父组件刷新文档内容
      emit('backtrack-success', props.documentId);
      closeDialog(); // 关闭对话框，返回文档编辑页面
    } else {
      ElMessage.error('回溯失败，无权限');
    }
  } catch (err) {
    // 用户取消回溯或发生错误
    if (err !== 'cancel') {
      console.error('Failed to backtrack to version:', err);
    }
  }
};

// 关闭对话框
const closeDialog = () => {
  emit('update:visible', false);
};

// 处理页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page;
  fetchVersions();
};

// 处理每页条数变化
const handleSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1;
  fetchVersions();
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });
};

// 监听对话框可见性变化
watch(
  () => props.visible,
  (newVal) => {
    if (newVal) {
      fetchVersions();
    }
  }
);

// 监听文档ID变化
watch(
  () => props.documentId,
  (newVal) => {
    if (props.visible && newVal) {
      currentPage.value = 1;
      fetchVersions();
    }
  }
);
</script>

<template>
  <el-dialog
    title="文档历史版本"
    v-model="props.visible"
    @update:modelValue="emit('update:visible', $event)"
    width="60%"
    destroy-on-close
    class="version-history-dialog"
  >
    <div class="version-history-container">
      <div v-if="loading" class="loading-state">
        <el-skeleton :rows="5" animated />
      </div>
      <div v-else-if="versions.length === 0" class="empty-state">
        <p>暂无历史版本记录</p>
      </div>
      <div v-else class="version-list">
        <el-table :data="versions" style="width: 100%">
          <el-table-column prop="version" label="版本号" width="80" />
          <el-table-column label="创建时间" width="180">
            <template #default="{ row }">
              {{ formatDate(row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="标题" width="180">
            <template #default="{ row }">
              {{ row.title || '无标题' }}
            </template>
          </el-table-column>
          <el-table-column label="备注" min-width="200">
            <template #default="{ row }">
              {{ row.remark || '无备注' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="240">
            <template #default="{ row }">
              <div class="action-buttons">
                <el-button type="primary" size="small" @click="viewVersion(row)" class="view-btn">
                  查看
                </el-button>
                <el-button type="warning" size="small" @click="backtrackVersion(row)" class="backtrack-btn">
                  回溯
                </el-button>
                <el-button type="danger" size="small" @click="deleteVersion(row)" class="delete-btn">
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[5, 10, 20, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<style scoped>
.version-history-dialog :deep(.el-dialog__header) {
  padding: 20px 24px;
  border-bottom: 1px solid #ebeef5;
  margin-right: 0;
}

.version-history-dialog :deep(.el-dialog__title) {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.version-history-dialog :deep(.el-dialog__body) {
  padding: 24px;
}

.version-history-dialog :deep(.el-dialog__headerbtn) {
  top: 20px;
  right: 20px;
}

.version-history-container {
  min-height: 300px;
}

.loading-state,
.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
}

.empty-state p {
  color: #909399;
  font-size: 14px;
}

.version-list :deep(.el-table) {
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.version-list :deep(.el-table__header-wrapper th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
  padding: 12px 0;
}

.version-list :deep(.el-table__row) {
  transition: background-color 0.3s;
}

.version-list :deep(.el-table__row:hover) {
  background-color: #f5f7fa;
}

.version-list :deep(.el-button) {
  padding: 8px 16px;
  font-size: 13px;
  border-radius: 4px;
  transition: all 0.3s;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.backtrack-btn {
  background-color: #e6a23c;
  border-color: #e6a23c;
}

.backtrack-btn:hover {
  background-color: #d48f1c;
  border-color: #d48f1c;
}

.delete-btn {
  background-color: #f56c6c;
  border-color: #f56c6c;
}

.delete-btn:hover {
  background-color: #e64242;
  border-color: #e64242;
}

.pagination-container :deep(.el-pagination) {
  padding: 16px 0;
  font-weight: normal;
}

.pagination-container :deep(.el-pagination .el-pagination__total) {
  margin-right: 16px;
}
</style>